﻿'
' Will Strohl (will.strohl@gmail.com)
' http://www.willstrohl.com
' http://dnntweet.codeplex.com
'
' Copyright (c) 2011, Will Strohl
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this 
' software and associated documentation files (the "Software"), to deal in the Software 
' without restriction, including without limitation the rights to use, copy, modify, 
' merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 
' permit persons to whom the Software is furnished to do so, subject to the following 
' conditions:
'
' The above copyright notice and this permission notice shall be included in all copies 
' or substantial portions of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
' INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
' PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
' HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
' OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'

Imports DotNetNuke.Entities.Modules
Imports DotNetNuke.Services.Exceptions
Imports System.Web.UI
Imports Twitterizer
Imports WillStrohl.Modules.Twitter.TwitterController

Namespace WillStrohl.Modules.Twitter

    Partial Public MustInherit Class ViewTwitterView
        Inherits WNSPortalModuleBase
        Implements IActionable

#Region " Private Members "

        Private Const c_MenuItem_Title As String = "MenuItem.Edit.Title"
        Private Const c_Edit As String = "Edit"

        Private p_OAuth_Token As String = Null.NullString
        Private p_OAuth_Secret As String = Null.NullString
        Private p_TwitterUsername As String = Null.NullString
        Private p_TwitterUserId As Integer = Null.NullInteger
        Private p_ShowAuthenticate As Boolean = Null.NullBoolean
        Private p_TokenResponse As OAuthTokenResponse = Nothing
        Private p_Tokens As OAuthTokens = Nothing
        Private p_SearchHandlerPath As String = Null.NullString

#End Region

#Region " Private Properties "

        Private ReadOnly Property OAuth_Token() As String
            Get
                If Not String.IsNullOrEmpty(Me.p_OAuth_Token) Then
                    Return Me.p_OAuth_Token
                End If

                Dim obj As Object = Request.Cookies(OAUTH_TOKEN_KEY)
                If Not obj Is Nothing Then
                    Me.p_OAuth_Token = obj.ToString
                End If

                Return Me.p_OAuth_Token
            End Get
        End Property

        Private ReadOnly Property OAuth_Secret() As String
            Get
                If Not String.IsNullOrEmpty(Me.p_OAuth_Secret) Then
                    Return Me.p_OAuth_Secret
                End If

                Dim obj As Object = Request.Cookies(OAUTH_VERIFIER_KEY)
                If Not obj Is Nothing Then
                    Me.p_OAuth_Secret = obj.ToString
                End If

                Return Me.p_OAuth_Secret
            End Get
        End Property

        Private ReadOnly Property TokenResponse() As OAuthTokenResponse
            Get
                Return Me.p_TokenResponse
            End Get
        End Property

        Private ReadOnly Property TwitterUsername() As String
            Get
                Return Me.p_TwitterUsername
            End Get
        End Property

        Private ReadOnly Property TwitterUserId() As Integer
            Get
                Return Me.p_TwitterUserId
            End Get
        End Property

        Private ReadOnly Property Tokens() As OAuthTokens
            Get
                If Not Me.p_Tokens Is Nothing Then
                    Return Me.p_Tokens
                End If

                If Not String.IsNullOrEmpty(Me.OAuth_Token) And Not String.IsNullOrEmpty(Me.OAuth_Secret) Then
                    Me.p_Tokens = New OAuthTokens
                    Me.p_Tokens.AccessToken = Me.OAuth_Token
                    Me.p_Tokens.AccessTokenSecret = Me.OAuth_Secret
                    Me.p_Tokens.ConsumerKey = Me.TwitterConsumerKey
                    Me.p_Tokens.ConsumerSecret = Me.TwitterConsumerSecret
                End If

                Return Me.p_Tokens
            End Get
        End Property

#End Region

#Region " Public Properties "

        Protected ReadOnly Property ShowAuthenticate() As Boolean
            Get
                Return Me.p_ShowAuthenticate
            End Get
        End Property

        Protected ReadOnly Property SearchHandlerPath() As String
            Get
                If Not String.IsNullOrEmpty(Me.p_SearchHandlerPath) Then
                    Return Me.p_SearchHandlerPath
                End If

                If Request.IsSecureConnection Then
                    Me.p_SearchHandlerPath = String.Concat("https://", Request.Url.Host, Me.ControlPath, "search.ashx")
                Else
                    Me.p_SearchHandlerPath = String.Concat("http://", Request.Url.Host, Me.ControlPath, "search.ashx")
                End If

                Return Me.p_SearchHandlerPath
            End Get
        End Property

#End Region

#Region " Event Handlers "

        Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try

                Me.ImportPlugins()

                ' bind any data and/or localization to the module on page loads
                Me.BindData()

            Catch exc As Exception ' Module failed to load
                ProcessModuleLoadException(Me, exc, Me.IsEditable)
            End Try

        End Sub

#End Region

#Region " Helper Methods "

        Private Sub ImportPlugins()

            ' load the css on page loads
            If Me.jQueryUIHosted Then
                ' cannot use the core method to import a stylesheet, because it doesn't allow references to external stylesheets
                'PageBase.RegisterStyleSheet(Me.Page, String.Format(HOSTED_JQUERY_UI_CSS_URL, Me.jQueryUITheme))
                Me.Page.Header.Controls.Add(New LiteralControl(String.Format(CSS_TAG_INCLUDE_FORMAT, String.Format(HOSTED_JQUERY_UI_CSS_URL, Me.jQueryUITheme))))
            Else
                PageBase.RegisterStyleSheet(Me.Page, String.Concat(Me.ControlPath, String.Format("css/{0}/jquery-ui.css", Me.jQueryUITheme)))
            End If

        End Sub

        Private Sub LocalizeModule()



        End Sub

        Private Sub BindData()

            Me.LocalizeModule()

            '
            ' authenticate to twitter
            '

            'If String.IsNullOrEmpty(Me.OAuth_Token) Then

            '    Me.GetTwitterAuthorization()

            'Else

            '    Dim tokens As OAuthTokenResponse = _
            '        OAuthUtility.GetAccessToken(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, Request(OAUTH_TOKEN_KEY), Request(OAUTH_VERIFIER_KEY))

            '    ' save tokens
            '    SaveCookie(OAUTH_TOKEN_KEY, tokens.Token)
            '    SaveCookie(OAUTH_VERIFIER_KEY, tokens.TokenSecret)

            'End If

            '
            ' connect to twitter
            '

            If Not String.IsNullOrEmpty(Me.OAuth_Token) And Not String.IsNullOrEmpty(Me.OAuth_Secret) Then

                '' try to send an update to twitter
                'Dim oStatus As TwitterStatus = TwitterStatus.Update(Me.Tokens, "Hello World")
                'If Not oStatus Is Nothing Then
                '    Me.phContent.Controls.Add(New LiteralControl("Hello World at: " & oStatus.CreatedDate.ToString & "<br />"))
                'End If

                '' try to view someone's time line
                'Dim sb As New StringBuilder
                'For Each tweet As TwitterSearchResult In TwitterSearch.Search("FROM:techbubble")
                '    sb.AppendLine(tweet.FromUserScreenName & " : " & tweet.Text & "<br />")
                'Next
                'Me.phContent.Controls.Add(New LiteralControl(sb.ToString))

            Else

                Me.p_ShowAuthenticate = True

            End If

            ' If we want to do this server-side, use this method
            'Me.BuildSearchResults()

            If String.IsNullOrEmpty(Me.TwitterSearchTerms) Then
                Skin.AddModuleMessage(Me, Me.GetLocalizedString("MissingModuleSettings.Text"), Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
            End If

        End Sub

        '<System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert, Unrestricted:=True)> _
        'Private Sub GetTwitterAuthorization()

        '    ' First, get the request token
        '    Dim authorizationTokens As OAuthTokenResponse = OAuthUtility.GetRequestToken( _
        '        TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, NavigateURL)

        '    Dim authorizeUri As Uri = OAuthUtility.BuildAuthorizationUri(authorizationTokens.Token)

        '    Me.p_OAuth_Token = authorizationTokens.Token
        '    Me.p_OAuth_Secret = authorizationTokens.TokenSecret

        '    ' Comment this line to prompt the user to continue before directing them to twitter
        '    Response.Redirect(authorizeUri.AbsoluteUri, True)

        'End Sub

        Private Sub BuildSearchResults()

            Me.phContent.Controls.Add(New LiteralControl(SearchAPI.GetSearchResults(Me.TwitterSearchTerms, Me.GetLocalizedString("Author.Said"))))

        End Sub

#End Region

#Region " IActionable Implementation "

        Public ReadOnly Property ModuleActions() As DotNetNuke.Entities.Modules.Actions.ModuleActionCollection Implements IActionable.ModuleActions
            Get
                Dim Actions As New Actions.ModuleActionCollection
                Actions.Add(GetNextActionID, Me.GetLocalizedString(c_MenuItem_Title), _
                    String.Empty, String.Empty, String.Empty, _
                    EditUrl(String.Empty, String.Empty, c_Edit), _
                    False, DotNetNuke.Security.SecurityAccessLevel.Edit, True, False)
                Return Actions
            End Get
        End Property

#End Region

    End Class

End Namespace